package leaveSystem.controller;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.mail.MessagingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mysql.jdbc.Connection;


import leaveSystem.bizlogic.LeaveManager;
import leaveSystem.bizlogic.WorkScheduleManager;
import leaveSystem.dao.DAOFactory;
import leaveSystem.dao.mysql.Compensation_TrackingDaoImpl;
import leaveSystem.model.ApplyLeaveFormBean;
import leaveSystem.model.CompensationTracking;
import leaveSystem.model.Employee;
import leaveSystem.model.EmployeeWorkschedule;
import leaveSystem.model.Leave;
import leaveSystem.utility.DateUtility;
import leaveSystem.utility.SendEmail;

/**
 * Servlet implementation class CompensationServlet
 */
@WebServlet("/CompensationServlet")
public class CompensationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CompensationServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
	
HttpSession session = request.getSession();
Employee resultEmp = (Employee) session.getAttribute("currentSessionUser");

Connection conn = (Connection) DAOFactory.getDatabaseConnection();
		Compensation_TrackingDaoImpl cdip = new Compensation_TrackingDaoImpl();
		ArrayList<CompensationTracking> leaveDetails = cdip.LoadLeaveHistory(conn,resultEmp);
		String destination = "/Compensation.jsp";
		request.setAttribute("CompensationLeave",leaveDetails);
		RequestDispatcher rd = getServletContext().getRequestDispatcher(destination);
		rd.forward(request, response);
		
		/*WorkScheduleManager scheduleManager = new WorkScheduleManager();
		List<CompensationTracking> leaveDetails = scheduleManager.loadAll(null);
		String destination = "/Compensation.jsp";
		request.setAttribute("CompensationLeave",leaveDetails);
		RequestDispatcher rd = getServletContext().getRequestDispatcher(destination);
		rd.forward(request, response);*/
	}

	/**
	 * @param  
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Employee resultEmp = (Employee) session.getAttribute("currentSessionUser");
		ApplyLeaveFormBean fbean = (ApplyLeaveFormBean)session.getAttribute("ApplyFormBean");
		DateUtility date = new DateUtility();
		Date today = date.getDate();
		
		int totOT= Integer.parseInt(request.getParameter("overtime"));		
			
		Leave saveLve = new Leave();
		if(fbean.getLeaveId()!=0)
			saveLve.setLeaveId(fbean.getLeaveId());
		
		saveLve.setEmployeeId(resultEmp.getEmployeeId());
		saveLve.setLeaveReason(fbean.getLeaveReason());
		saveLve.setLeaveTypeId(fbean.getLeaveType());
		saveLve.setLeaveStartDate(fbean.getFromDate());
		saveLve.setLeaveEndDate(fbean.getToDate());
		saveLve.setStatus("Applied");
		
		if(fbean.getLeaveId()!=0)
			saveLve.setStatus("Updated");
		saveLve.setRemarks(null);//form
		saveLve.setCreatedBy(resultEmp.getUsername());//login user
		saveLve.setCreatedOn(today);//today date
		saveLve.setModifiedBy(resultEmp.getUsername());//login user
		saveLve.setModifiedOn(today);
		saveLve.setRemainingLeaves( totOT/4);
				
//need to save to leave table		
		LeaveManager lmanager = new LeaveManager();
		if(fbean.getLeaveId()==0){
			lmanager.createLeave(saveLve);
			System.out.println(">>create<<");
		}
		else{
			lmanager.updateLeave(saveLve);
			System.out.println(">>update<<");
		}
		RequestDispatcher rs = request.getRequestDispatcher("welcome.jsp");
		rs.forward(request, response);
//>>>>>>>>>>>>>>>>>>>>>>>		
		//SENDING EMAIL
		/*
		
		String EmplName = request.getParameter("empName");
		@SuppressWarnings("unused")
		//String startDate=request.getParameter("demo1");
		//String endDate = request.getParameter("demo2");
		//String dateOfException = request.getParameter("demo3");
		String recipients[] = {"badri3590@gmail.com","rageshrnair.666@gmail.com"};
		SendEmail e = new SendEmail();
		String message = EmplName + " has applied for Compensation leave";
		try {
		    BufferedWriter out = new BufferedWriter(new FileWriter("C:\\Alert.txt"));
		    out.write(message);
		    out.close();
		} catch (IOException e2) {
		}
		try {
			e.sendSSLMessage(recipients, "Compensation Leave Applied", message, "xxxx@gmail.com");
		} catch (MessagingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		WorkScheduleManager WM=new WorkScheduleManager();
		EmployeeWorkschedule entity=new EmployeeWorkschedule();
		Connection con = null;

		
		CompensationTracking compensationTaking = new CompensationTracking("1",
				"11/10/2011",request.getParameter("leaveStart").toString(),
				request.getParameter("leaveEnd").toString(),
				request.getParameter("tol"),
				request.getParameter("reason").toString(),
				"PENDING",
				request.getParameter("managerName").toString(),date.getDate().toString());
		
		
		
		Connection conn = (Connection) DAOFactory.getDatabaseConnection();
		Compensation_TrackingDaoImpl cdip = new Compensation_TrackingDaoImpl();
		Employee employee = null ;
		try {
			cdip.createEmployeeLeaveMap(conn, employee, compensationTaking);
			cdip.create(con, compensationTaking);
			
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		int compensationHoursIn=0;
		entity.setCompensationHours(compensationHoursIn);
		entity.setRemarks("remarksIn");*/
		
	}

	

}
